from pydantic import BaseModel, Field, ConfigDict
from datetime import datetime, date
from typing import Optional, List, Dict, Any
from enum import Enum
from decimal import Decimal


class RelationshipType(str, Enum):
    """关系类型枚举"""
    PARENT_CHILD = "parent_child"
    SPOUSE = "spouse"
    SIBLING = "sibling"
    GRANDPARENT_GRANDCHILD = "grandparent_grandchild"
    GRANDPARENT_GRANDCHILD_ZEN = "grandparent_grandchild_zen"


class PersonRole(str, Enum):
    """人员角色枚举"""
    FATHER = "father"
    MOTHER = "mother"
    SON = "son"
    DAUGHTER = "daughter"
    SPOUSE = "spouse"
    
    # 传统的兄弟姐妲角色（保持向后兼容）
    BROTHER = "brother"
    SISTER = "sister"
    
    # 精细化的兄弟姐妲角色
    # ELDER_BROTHER = "elder_brother"  # 哥哥/兄
    # YOUNGER_BROTHER = "younger_brother"  # 弟弟/弟
    # ELDER_SISTER = "elder_sister"  # 姐姐/姐
    # YOUNGER_SISTER = "younger_sister"  # 妹妹/妹
    ELDER_BROTHER = "gege"
    YOUNGER_BROTHER = "didi"
    ELDER_SISTER = "jiejie"
    YOUNGER_SISTER = "meimei"
    
    GRANDFATHER = "grandfather"
    GRANDMOTHER = "grandmother"
    GRANDSON = "grandson"
    GRANDDAUGHTER = "granddaughter"
    
    GRAND_GRANDFATHER = "zengzufu"
    GRAND_GRANDMOTHER = "zengzumu"
    GRANDSON_SON = "zengsun"
    GRANDDAUGHTER_DAUGHTER = "zengsunnv"


class GenderType(int, Enum):
    """性别类型枚举"""
    UNKNOWN = 0
    MALE = 1
    FEMALE = 2


class FamilyTreeFieldsMixin(BaseModel):
    """族谱公共字段Mixin类"""
    taboo_name: Optional[str] = Field(None, description="名讳", max_length=50)
    ranking_character: Optional[str] = Field(None, description="排行字", max_length=20)
    birth_date: Optional[date] = Field(None, description="出生日期")
    gender: Optional[int] = Field(GenderType.UNKNOWN.value, description="性别 0-未知 1-男 2-女")
    avatar: Optional[str] = Field(None, description="头像URL", max_length=500)
    generation: Optional[int] = Field(None, description="第几代", ge=1)
    biography: Optional[str] = Field(None, description="生平简介")
    death_date: Optional[date] = Field(None, description="死亡时间")
    longitude: Optional[Decimal] = Field(None, description="墓地经度坐标", ge=Decimal('-180'), le=Decimal('180'))
    latitude: Optional[Decimal] = Field(None, description="墓地纬度坐标", ge=Decimal('-90'), le=Decimal('90'))
    grave_address: Optional[str] = Field(None, description="墓地地址名称", max_length=500)
    grave_images: Optional[List[str]] = Field(None, description="墓地周边图片URL数组")
    images: Optional[List[str]] = Field(None, description="相关图片URL数组")
    shop_id: Optional[str] = Field(None, description="店铺ID", max_length=36)
    tenant_id: Optional[str] = Field(None, description="租户ID", max_length=36)


class FamilyTreeBase(FamilyTreeFieldsMixin):
    """族谱基础模型（创建时用）"""
    name: str = Field(..., description="姓名（必填）", min_length=1, max_length=50)


class CreateMixin(BaseModel):
    """创建操作公共字段Mixin类"""
    create_by: Optional[str] = Field(None, description="创建人ID")
    
    model_config = ConfigDict(from_attributes=True)


class FamilyTreeCreate(FamilyTreeBase, CreateMixin):
    """创建族谱成员的请求模型"""
    pass


class FamilyTreeUpdate(FamilyTreeFieldsMixin):
    """更新族谱成员的请求模型（所有字段均为可选）"""
    name: Optional[str] = Field(None, description="姓名", min_length=1, max_length=50)
    update_by: Optional[str] = Field(None, description="修改人ID")
    
    model_config = ConfigDict(from_attributes=True)


class FamilyTreeInfo(FamilyTreeBase):
    """族谱成员详细信息响应模型"""
    id: str = Field(..., description="成员ID")
    create_by: Optional[str] = Field(None, description="创建人ID")
    update_by: Optional[str] = Field(None, description="修改人ID")
    create_time: datetime = Field(..., description="创建时间")
    update_time: datetime = Field(..., description="修改时间")
    status: int = Field(..., description="状态 1-正常 0-删除")
    deleted_at: Optional[datetime] = Field(None, description="删除时间")
    
    model_config = ConfigDict(from_attributes=True)


class PaginationMixin(BaseModel):
    """分页公共参数Mixin类"""
    page_index: int = Field(1, description="页码", ge=1)
    page_size: int = Field(10, description="每页数量", ge=1, le=1000)


class FamilyTreeQuery(PaginationMixin):
    """族谱查询参数模型"""
    name: Optional[str] = Field(None, description="姓名关键词")
    generation: Optional[int] = Field(None, description="代数筛选")
    shop_id: Optional[str] = Field(None, description="店铺筛选")
    tenant_id: Optional[str] = Field(None, description="租户筛选")
    status: Optional[int] = Field(1, description="状态筛选")
    
    model_config = ConfigDict(from_attributes=True)


# 关系相关的Schema
class FamilyRelationshipBase(BaseModel):
    """家族关系基础模型"""
    person_id: str = Field(..., description="人员ID")
    related_person_id: str = Field(..., description="关系人ID")
    relationship_type: RelationshipType = Field(..., description="关系类型")
    person_role: PersonRole = Field(..., description="person_id的角色")
    related_person_role: PersonRole = Field(..., description="related_person_id的角色")
    shop_id: Optional[str] = Field(None, description="店铺ID（可选，不填则自动从person信息继承）")
    tenant_id: Optional[str] = Field(None, description="租户ID（可选，不填则自动从person信息继承）")


class FamilyRelationshipCreate(FamilyRelationshipBase, CreateMixin):
    """创建家族关系的请求模型"""
    pass


class BatchFamilyRelationshipCreate(BaseModel):
    """批量创建家族关系的请求模型"""
    relationships: List[FamilyRelationshipBase] = Field(..., description="家族关系列表", min_length=1)
    create_by: Optional[str] = Field(None, description="创建人 ID")
    
    model_config = ConfigDict(from_attributes=True)


class FamilyRelationshipInfo(FamilyRelationshipBase):
    """家族关系详细信息响应模型"""
    id: str = Field(..., description="关系ID")
    person_name: Optional[str] = Field(None, description="人员名称")
    related_person_name: Optional[str] = Field(None, description="关系人名称")
    shop_id: Optional[str] = Field(None, description="店铺ID")
    tenant_id: Optional[str] = Field(None, description="租户ID")
    create_by: Optional[str] = Field(None, description="创建人ID")
    create_time: datetime = Field(..., description="创建时间")
    update_time: datetime = Field(..., description="修改时间")
    status: int = Field(..., description="状态 1-正常 0-删除")
    
    model_config = ConfigDict(from_attributes=True)


class FamilyRelationshipQuery(PaginationMixin):
    """关系查询参数模型"""
    person_id: Optional[str] = Field(None, description="人员ID")
    relationship_type: Optional[RelationshipType] = Field(None, description="关系类型")
    shop_id: Optional[str] = Field(None, description="店铺筛选")
    tenant_id: Optional[str] = Field(None, description="租户筛选")
    
    model_config = ConfigDict(from_attributes=True)


class BatchCreateResult(BaseModel):
    """批量创建结果模型"""
    total_requested: int = Field(..., description="总请求数量")
    created_count: int = Field(..., description="成功创建数量")
    skipped_count: int = Field(..., description="跳过数量（已存在）")
    created_relationships: List[FamilyRelationshipInfo] = Field([], description="成功创建的关系列表")
    skipped_relationships: List[dict] = Field([], description="跳过的关系列表")
    
    model_config = ConfigDict(from_attributes=True)


class FamilyTreeWithRelations(FamilyTreeInfo):
    """包含关系信息的族谱成员模型"""
    relationships: Optional[List[FamilyRelationshipInfo]] = Field(None, description="关系列表")
    
    model_config = ConfigDict(from_attributes=True)


class FamilyTreeListResponse(BaseModel):
    """族谱列表响应模型"""
    total: int = Field(..., description="总数量")
    items: List[FamilyTreeInfo] = Field(..., description="成员列表")
    
    model_config = ConfigDict(from_attributes=True)


class AncestorsDescendantsQuery(BaseModel):
    """祖先和后代查询请求模型"""
    max_generations: int = Field(5, description="最大代数", ge=1, le=10)
    shop_id: Optional[str] = Field(None, description="商店ID（多租户筛选）")
    tenant_id: Optional[str] = Field(None, description="租户ID（多租户筛选）")
    
    model_config = ConfigDict(from_attributes=True)


class GenerationQuery(BaseModel):
    """根据代数查询请求模型"""
    shop_id: Optional[str] = Field(None, description="店铺ID（多租户筛选）")
    tenant_id: Optional[str] = Field(None, description="租户ID（多租户筛选）")
    
    model_config = ConfigDict(from_attributes=True)


class StructureQuery(BaseModel):
    """族谱结构查询请求模型"""
    root_person_id: Optional[str] = Field(None, description="根节点人员ID（可选）")
    shop_id: Optional[str] = Field(None, description="店铺ID（多租户筛选）")
    tenant_id: Optional[str] = Field(None, description="租户ID（多租户筛选）")
    
    model_config = ConfigDict(from_attributes=True)


class NearbyGraveQuery(PaginationMixin):
    """附近墓地查询参数模型"""
    longitude: Decimal = Field(..., description="中心点经度坐标", ge=Decimal('-180'), le=Decimal('180'))
    latitude: Decimal = Field(..., description="中心点纬度坐标", ge=Decimal('-90'), le=Decimal('90'))
    radius: int = Field(500, description="查找半径（米）", ge=1, le=50000)
    shop_id: Optional[str] = Field(None, description="店铺筛选")
    tenant_id: Optional[str] = Field(None, description="租户筛选")
    
    model_config = ConfigDict(from_attributes=True)


class GraveLocationSimple(BaseModel):
    """墓地位置简化信息响应模型"""
    id: str = Field(..., description="成员ID")
    name: str = Field(..., description="姓名")
    taboo_name: Optional[str] = Field(None, description="名讳")
    generation: Optional[int] = Field(None, description="第几代")
    gender: Optional[int] = Field(None, description="性别 0-未知 1-男 2-女")
    longitude: Optional[Decimal] = Field(None, description="墓地经度坐标")
    latitude: Optional[Decimal] = Field(None, description="墓地纬度坐标")
    grave_address: Optional[str] = Field(None, description="墓地地址名称")
    distance: Optional[Decimal] = Field(None, description="距离中心点距离（米）")
    
    model_config = ConfigDict(from_attributes=True)
